﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components;
using System.Diagnostics.CodeAnalysis;
using BBCore.Core.Models.Samples;
using BBCore.Application.Samples;
using BBCore.Application.OracleApplication.BOM.Interface;
using BBCore.Server.Data;
using Microsoft.JSInterop;
using DocumentFormat.OpenXml.EMMA;
using FluentValidation;
using BBCore.Application.Interface;
using Microsoft.AspNetCore.Authorization;
using BBCore.Infrastructure.Helps;

namespace BBCore.Server.Components.Pages.Samples
{
    public partial class MasterDetail
    {
        ZDL_HYJ_MASTER_HEAD Model = new();
        [Parameter]
        public string? p_find { get; set; }
        [Parameter]
        public int KingNo { get; set; }
        /// <summary>
        /// 流水号
        /// </summary>
        public int kingno;
        [Inject]
        [NotNull]
        private ToastService? ToastService { get; set; }
        [Inject]
        [NotNull]
        private SwalService? SwalService { get; set; }

        [Inject]
        [NotNull]
        private IMasterDetailService? IMasterDetailService { get; set; }

        public bool IsDisabled { get; set; } = false;
        //protected override void OnAfterRender(bool firstRender)
        //{
        //    if (firstRender)
        //    {
        //        show();
        //        StateHasChanged();
        //    }


        //}
        /// <summary>
        /// 控制按钮是否显示
        /// </summary>
        //private async void show()
        //{
        //    var username = await IGetLoginUserNameService.GetLoginUserNameAsync(AuthenticationStateProvider);
        //    if (username == "admin")
        //    {
        //        IsDisabled = false;
        //    }
        //    else
        //    {
        //        IsDisabled = true;
        //    }
        //}



        private void AddNewRow()
        {
            var validator = new ZDL_HYJ_MASTER_HEADValidator();
            var validationResult = validator.Validate(Model);

            if (!validationResult.IsValid)
            {
                //return;
            }
            else
            {
                Model!.ZBJB_ITEMS!.Add(new ZDL_HYJ_DETAIL_BODY());
            }


        }
        private async Task OnValidSubmit(EditContext context)
        {
            try
            {
                var validator = new ZDL_HYJ_MASTER_HEADValidator();
                var validationResult = validator.Validate(Model);

                if (!validationResult.IsValid)
                {
                    validator.ValidateAndThrow(Model);
                }
                else
                {
                    if (KingNo == 0) //新增
                    {
                        var items = (ZDL_HYJ_MASTER_HEAD)context.Model;
                        IMasterDetailService.CascadeInsertSave(items, out kingno);
                        KingNo = kingno;
                        await ToastService.Show(new ToastOption()
                        {
                            Category = ToastCategory.Success,
                            Title = "保存成功",
                            Content = "保存数据成功,4秒后自动关闭"
                        });
                    }
                    else //编辑
                    {
                        var items = (ZDL_HYJ_MASTER_HEAD)context.Model;
                        IMasterDetailService.CascadeUpdateSave(items, KingNo);
                        await ToastService.Show(new ToastOption()
                        {
                            Category = ToastCategory.Success,
                            Title = "更新成功",
                            Content = "保存数据成功,4秒后自动关闭"
                        });
                    }

                }
            }
            catch (Exception ex)
            {
                await SwalService.Show(new SwalOption()
                {
                    Category = SwalCategory.Error,
                    Title = "保存出错了!",
                    Content = "出错信息:" + ex.Message,
                    ShowFooter = true,
                    FooterTemplate = BootstrapDynamicComponent.CreateComponent<BBCore.Server.Components.Pages.ContactAdmin>().Render()
                });
            }
        }
        [Inject]
        [NotNull]
        public MessageService? MessageService { get; set; }
        [Inject]
        private IMsiService? IMsiService { get; set; }

        [NotNull]
        private BootstrapInput<string?>? inputLEVEL2 { get; set; }
        async Task Item_ValueChangeAsync(ZDL_HYJ_DETAIL_BODY detail, string? val)
        {
            if (!string.IsNullOrEmpty(val))
            {
                var lit = IMsiService?.GetMsi(Model.ORG_ID, val);
                if (lit != null)
                {
                    detail.DESCRIPTION = lit.DESCRIPTION;
                    detail.ITEM_TYPE = lit.ITEM_TYPE;
                    await inputLEVEL2.FocusAsync();//获得焦点
                }
                else
                {
                    await MessageService.Show(new MessageOption()
                    {
                        Color = Color.Danger,
                        Content = "出错了,请检查组织和部品号是否正确"
                    });
                }

            }
            await Task.CompletedTask;

        }
        /// <summary>
        /// 根据流水号查询
        /// </summary>
        //[Authorize(policy: "IsAdmin")]
        private void Query()
        {
            var tmpModel = IMasterDetailService.GetZDL_BKC(Convert.ToInt32(p_find));

            if (tmpModel == null)
            {
                MessageService.Show(new MessageOption()
                {
                    Color = Color.Danger,
                    Content = "出错了,请批次号不存在!"
                });
            }
            else
            {
                Model = tmpModel;
                KingNo = Model.ZDL_BKC_JOB_HEAD_ID;
            }
        }
        /// <summary>
        /// 导航回当前页并刷新 
        /// </summary>
        private void RefreshPage()
        {
            // 获取当前URL
            var currentUrl = NavigationManager.Uri;
            // 导航回当前页并刷新            
            NavigationManager.NavigateTo(currentUrl, forceLoad: true);
        }
        /// <summary>
        /// 模板下载
        /// </summary>
        /// <returns></returns>
        private async Task tempDownload()
        {
            var filepath = await IExporterAndImporterService.TemplateDownloadAsync<ZDL_HYJ_DETAIL_BODY>();
            string fileName = Path.GetFileName(filepath);
            await DownloadService.DownloadFromFileAsync(fileName, filepath);
            await ToastService.Show(new ToastOption()
            {
                Title = "模板下载",
                Content = "模板已下载,4秒后自动关闭",
                Category = ToastCategory.Success
            });
        }
        /// <summary>
        /// 数据导入
        /// </summary>
        /// <param name="uploadFile"></param>
        /// <returns></returns>
        private async Task DataImport(UploadFile uploadFile)
        {
            if (uploadFile.GetExtension() != ".xlsx")
            {
                await SwalService.Show(new SwalOption()
                {
                    Content = "导入出错了,只支持上传.xlsx格式的excel文件",
                    Category = SwalCategory.Error
                });
                return;
            }
            using MemoryStream stream = new MemoryStream();
            var items = await IExporterAndImporterService.importResultAsync<ZDL_HYJ_DETAIL_BODY>(uploadFile, stream);
            if (items.RowErrors.Count > 0)//导入验证出错
            {
                var filepath = await IExporterAndImporterService.TemplateErrorInfoAsync<ZDL_HYJ_DETAIL_BODY>(items.RowErrors);
                string fileName = Path.GetFileName(filepath);
                await DownloadService.DownloadFromFileAsync(fileName, filepath);
                await SwalService.Show(new SwalOption()
                {
                    Content = "导入验证出错,请查看具体的出错信息",
                    Category = SwalCategory.Error
                });
            }
            else
            {
                var lst = IMasterDetailService.GetZDL_BKC_BODY_DETAIL(items.Data);
                //合并list
                Model.ZBJB_ITEMS!.AddRange(lst!); //items.Data
                StateHasChanged();
            }
        }

    }
}
